#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
专门处理C_Header_Statistics.prefab文件中遗漏的中文节点
"""

import re
import shutil
from pathlib import Path

# 遗漏的节点名称映射表
MISSING_NODE_MAPPING = {
    "赔率背景色": "Odds_Background",
    "赔率背景色-值": "Odds_Background_Value", 
    "标题节点1": "Header_Node_1",
}

def chinese_to_unity_unicode(chinese_text):
    """将中文字符串转换为Unity格式的Unicode转义序列（大写）"""
    unicode_escaped = chinese_text.encode('unicode_escape').decode('ascii')
    # 将小写的unicode转义序列转换为大写
    return re.sub(r'\\u([0-9a-f]{4})', lambda m: f'\\u{m.group(1).upper()}', unicode_escaped)

def process_header_statistics():
    """处理C_Header_Statistics.prefab文件"""
    file_path = Path("Assets/Prefabs/C_Header_Statistics.prefab")
    
    if not file_path.exists():
        print(f"文件不存在: {file_path}")
        return False
    
    print(f"处理文件: {file_path}")
    
    # 创建备份
    backup_path = file_path.with_suffix('.prefab.backup2')
    shutil.copy2(file_path, backup_path)
    print(f"创建备份: {backup_path}")
    
    # 读取文件内容
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    original_content = content
    total_replacements = 0
    
    # 处理每个映射
    for chinese_name, english_name in MISSING_NODE_MAPPING.items():
        unity_unicode = chinese_to_unity_unicode(chinese_name)
        pattern = rf'm_Name: "{re.escape(unity_unicode)}"'
        replacement = f'm_Name: "{english_name}"'
        
        # 计算替换次数
        matches = re.findall(pattern, content)
        if matches:
            content = re.sub(pattern, replacement, content)
            count = len(matches)
            total_replacements += count
            print(f"✓ 替换: {chinese_name} -> {english_name} ({count}次)")
        else:
            print(f"✗ 未找到: {chinese_name}")
    
    # 保存修改后的文件
    if content != original_content:
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f"\n✓ 文件已更新，总共替换了 {total_replacements} 个节点名称")
        return True
    else:
        print("\n✗ 没有进行任何替换")
        return False

def verify_result():
    """验证处理结果"""
    file_path = Path("Assets/Prefabs/C_Header_Statistics.prefab")
    
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    print("\n=== 验证结果 ===")
    unicode_patterns = re.findall(r'm_Name: "([^"]*\\u[0-9a-fA-F]{4}[^"]*)"', content)
    
    if unicode_patterns:
        print(f"⚠️  仍有 {len(unicode_patterns)} 个Unicode编码的中文节点:")
        for i, name in enumerate(unicode_patterns):
            print(f"  {i+1}. {name}")
    else:
        print("✓ 所有Unicode编码的中文节点都已处理完成")

if __name__ == "__main__":
    if process_header_statistics():
        verify_result()
    else:
        print("处理失败") 